﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SharpTeam.Crm.SkypeDialer.Configuration;
using System.Net;
using System.Web.Services.Protocols;

namespace SharpTeam.Crm.SkypeDialer.ConfigurationManager
{
    public partial class LoginForm : Form
    {
        private const string _errorConnectingCrmServer = "Error connecting CRM server";

        public LoginForm()
        {
            InitializeComponent();

#if (DEBUG)
            tb_server_url.Text = "http://62.173.132.150:3006";
#endif
        }

        internal string ServerUrl { get; private set; }

        internal ICredentials Credentials { get; private set; }

        private void chb_defaultcred_CheckedChanged(object sender, EventArgs e)
        {
            bool defcred = chb_defaultcred.Checked;

            tb_domain.Enabled = !defcred;
            tb_pwd.Enabled = !defcred;
            tb_username.Enabled = !defcred;
            lbl_domain.Enabled = !defcred;
            lbl_pwd.Enabled = !defcred;
            lbl_username.Enabled = !defcred;
        }

        private void bn_cancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        private void bn_connect_Click(object sender, EventArgs e)
        {
            ServerUrl = tb_server_url.Text;
            Credentials = chb_defaultcred.Checked? CredentialCache.DefaultCredentials: new NetworkCredential(tb_username.Text, tb_pwd.Text, tb_domain.Text);

            try
            {
                CrmConnection.CheckDiscoveryService(ServerUrl, Credentials);

                DialogResult = DialogResult.OK;
            }
            catch(SoapException ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.Detail.InnerText, _errorConnectingCrmServer,
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, _errorConnectingCrmServer,
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
